package com.iflytek.aisol.audit.iflytek.strategy.manage.config;

import com.iflytek.aisol.audit.iflytek.strategy.manage.common.entity.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 捕获所有运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public R<Object> handleRuntimeException(RuntimeException ex) {
        logger.error("RuntimeException occurred: ", ex);
        return R.failure("An unexpected error occurred: " + ex.getMessage());
    }

    /**
     * 捕获 SQL 异常
     */
    @ExceptionHandler(java.sql.SQLException.class)
    @ResponseBody
    public R<Object> handleSQLException(java.sql.SQLException ex) {
        logger.error("SQLException occurred: ", ex);
        return R.failure("A database error occurred: " + ex.getMessage());
    }

    /**
     * 捕获自定义异常
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public R<Object> handleCustomException(CustomException ex) {
        logger.error("CustomException occurred: ", ex);
        return R.failure(ex.getMessage());
    }

    /**
     * 捕获参数错误异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public R<Object> handleIllArgException(IllegalArgumentException ex) {
        logger.error("IllegalArgumentException occurred: ", ex);
        return R.failure("IllegalArgument : " + ex.getMessage());
    }

    /**
     * 捕获所有其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<Object> handleGenericException(Exception ex) {
        logger.error("其他异常: ", ex);
        return R.failure("其他异常: " + ex.getMessage());
    }
}
